import _ from 'lodash'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

export default defineStore('currentRole', () => {
  const _currentRole = ref<
    AccountAPIResponse.AccountConnectEnterprise['customerRoleVos'][0] | null
  >(null)

  const currentRole = computed(() => {
    if (!_currentRole.value) {
      const res = sessionStorage.getItem('currentRole')
      if (res) {
        _currentRole.value = JSON.parse(res)
      }
    }
    return _.cloneDeep(_currentRole.value)
  })

  const setCurrentRole = (
    role: AccountAPIResponse.AccountConnectEnterprise['customerRoleVos'][0],
  ) => {
    _currentRole.value = role
    sessionStorage.setItem('currentRole', JSON.stringify(role))
  }

  const clearCurrentRole = () => {
    _currentRole.value = null
    sessionStorage.removeItem('currentRole')
  }

  return {
    currentRole,
    setCurrentRole,
    clearCurrentRole,
  }
})
